package org.ncibi.cytoscape.metscape.action;

import java.awt.Component;
import java.awt.event.ActionEvent;

import javax.swing.JOptionPane;
import javax.swing.SwingConstants;

import org.ncibi.cytoscape.metscape.plugin.MetScapePlugin;
import org.ncibi.cytoscape.metscape.plugin.PluginRegistration;
import org.ncibi.cytoscape.metscape.ui.BuildNetworkPanel;
import org.ncibi.cytoscape.metscape.ui.RegistrationDialog;

import cytoscape.Cytoscape;
import cytoscape.util.CytoscapeAction;
import cytoscape.view.cytopanels.BiModalJSplitPane;
import cytoscape.view.cytopanels.CytoPanel;
import cytoscape.view.cytopanels.CytoPanelState;

@SuppressWarnings("serial")
public class BuildNetworkAction extends CytoscapeAction {
	
	private static final String NAME = "Build Network";
	private static BuildNetworkPanel panel;
	
	/**
	 * The constructor sets the text that should appear on the menu item.
	 */
	public BuildNetworkAction() {
		super(NAME);
	}

	/**
	 * This method is called when the user selects the menu item.
	 */
	public void actionPerformed(ActionEvent ae) {
		exec();
	}
	
	public static void exec(){
		if(!MetScapePlugin.isInitialized()) {
			MetScapePlugin.fetchServerVersion();
			if (MetScapePlugin.getServerVersion() == null){
				String message = "Unable to connect to MetScape server.";
				JOptionPane.showMessageDialog(Cytoscape.getDesktop(), message, "Server Unavailable", JOptionPane.WARNING_MESSAGE);
				return;
			}
			if (!MetScapePlugin.isVersionCompatible()) {
				String message = MetScapePlugin.getCompatiblityMessage();
				JOptionPane.showMessageDialog(Cytoscape.getDesktop(), message, "Incompatible Plugin", JOptionPane.ERROR_MESSAGE);
				return;
			}
			else if (!PluginRegistration.isPluginRegistered() && !PluginRegistration.isPluginRegistrationDeclined()) {
				RegistrationDialog dialog = new RegistrationDialog(Cytoscape.getDesktop());
				dialog.setVisible(true);
			}
		}
		
		if(panel == null) {
			panel = new BuildNetworkPanel();
		}
		CytoPanel cytoPanelWest = Cytoscape.getDesktop().getCytoPanel(
				SwingConstants.WEST);
		if(cytoPanelWest.indexOfComponent(panel) == -1) {
			cytoPanelWest.add("MetScape", panel);
			MetScapePlugin.getPluginData().setBuildNetworkPanelOpen(true);
		}
		cytoPanelWest.setSelectedIndex(cytoPanelWest
				.indexOfComponent("MetScape"));
		cytoPanelWest.setState(CytoPanelState.DOCK);
		BiModalJSplitPane splitPane = (BiModalJSplitPane) ((Component) cytoPanelWest).getParent();
		splitPane.setDividerLocation(panel.getParent().getMinimumSize().width);
	}

	public static BuildNetworkPanel getPanel() {
		return panel;
	}

	public static void setPanel(BuildNetworkPanel panel) {
		BuildNetworkAction.panel = panel;
	}
}
